﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace SlamCms.Web
{
	public class TagBrowserUrlHelper
	{
		private readonly UrlHelper urlHelper;
		private readonly HashSet<string> tags;
		private string tagBrowserId;
		private int page;
		private RouteValueDictionary routeValues;

		public TagBrowserUrlHelper(UrlHelper urlHelper, string tagBrowserId = null)
		{
			this.urlHelper = urlHelper;
			this.tags = new HashSet<string>();
			this.page = 0;
			this.tagBrowserId = tagBrowserId;
			this.routeValues = new RouteValueDictionary();
		}

		public TagBrowserUrlHelper AddTags(params string[] tags)
		{
			return this.AddTags(tags.AsEnumerable());
		}

		public TagBrowserUrlHelper AddTags(IEnumerable<string> tags)
		{
			foreach (var tag in tags)
			{
				if (!this.tags.Contains(tag))
					this.tags.Add(tag);
			}

			return this;
		}

		public TagBrowserUrlHelper RemoveTags(params string[] tags)
		{
			return this.RemoveTags(tags.AsEnumerable());
		}

		public TagBrowserUrlHelper RemoveTags(IEnumerable<string> tags)
		{
			foreach (var tag in tags)
			{
				if (this.tags.Contains(tag))
					this.tags.Remove(tag);
			}

			return this;
		}

		public TagBrowserUrlHelper Page(int page)
		{
			this.page = page;
			return this;
		}

		public TagBrowserUrlHelper TagBrowserId(string tagBrowserId)
		{
			this.tagBrowserId = tagBrowserId;
			return this;
		}

		public TagBrowserUrlHelper AddRouteValues(object routeValues)
		{
			foreach (var routeValue in new RouteValueDictionary(routeValues))
			{
				this.routeValues.Add(routeValue.Key, routeValue.Value);
			}

			return this;
		}

		public string Render()
		{
			string[] tags;

			if (this.page > 0)
			{
				var tagList = this.tags.ToList();
				tagList.Add(this.page.ToString());
				tags = tagList.ToArray();
			}
			else
				tags = this.tags.ToArray();

			return this.urlHelper.TagBrowser(this.tagBrowserId, tags, this.routeValues);
		}

		public override string ToString()
		{
			return this.Render();
		}
	}
}
